import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import javax.imageio.ImageIO;

import org.apache.commons.io.FileUtils;

includeTargets << grailsScript("Init")

def renderCirclePath = {
	file, output, exe ->
	def ns = new groovy.xml.Namespace("http://www.w3.org/2000/svg", "svg");
	def inkscape = new groovy.xml.Namespace("http://www.inkscape.org/namespaces/inkscape", "inkscape");
	def svg = new XmlParser().parse(file);

	def groups = svg.g.findAll {
		return it.attributes()[inkscape.groupmode] == 'layer';
	}
	def layers = [:]
	def layerObject = [:].withDefault { k -> [] }
	groups.each {
		def layerName = it.attributes()[inkscape.label];
		layers.put(layerName, it.'@id');
		it.path.each {
			obj ->
			layerObject[layerName] << obj.'@id'
		}
	}
	
	def workingCopy = File.createTempFile("inkscape",".svg")
	FileUtils.copyFile(file, workingCopy);
	
	def mergeLayer = {
		selections ->
		
		def command = [exe]
		selections.each {
			command += ["--select", it]
		}
		command += ["--verb=LayerMoveToPrev","--verb=FileSave", "--verb=FileClose", workingCopy]
		def proc = command.execute();
		println( command );
		proc.waitFor();
	}
	
	def intersection = {
		selections ->
		
		def command = [exe]
		selections.each {
			command += ["--select", it]
		}
		command += ["--verb=SelectionIntersect","--verb=FileSave", "--verb=FileClose", workingCopy]
		def proc = command.execute();
		println( command );
		proc.waitFor();
	}

	def export = {
		name, id, location ->
		
		def command = [exe, "--export-id", id, "--export-id-only", "--export-area="+location, "--export-png", output + "_" + name + ".png", workingCopy]
		println( command );
		proc = command.execute()
		def blah = proc.in.text
		def error = proc.err.text
		if( error ){
			println "FAILED ###\n${error}"
		}
	}

	def locations = ['south':'70:0:120:50'
		, 'south-west':'35:15:85:65'
		, 'west-south':'0:30:50:80'
		, 'west' : '0:60:50:110'
		, 'west-north' : '0:90:50:140'
		, 'north-west' : '35:105:85:155'
		, 'north' : '70:120:120:170'
		, 'south-east':'105:15:155:65'
		, 'east-south':'140:30:190:80'
		, 'east' : '140:60:190:110'
		, 'east-north' : '140:90:190:140'
		, 'north-east' : '105:105:155:155'];
	
	def run = {
		direction, layer ->
		
		workingCopy = File.createTempFile("inkscape_" + direction,".svg")
		FileUtils.copyFile(file, workingCopy);
		
		intersection(layerObject[direction]+layerObject[layer])
		
		mergeLayer(layerObject['decorations']);
		
		export(direction+'_'+layer, layers[layer], locations[direction]);
	}
		
	println( layers )
	if( layers['inner'] ){
		locations.keySet().each{ run(it, 'inner') }
	}
	if( layers['outer'] ){
		locations.keySet().each{ run(it, 'outer') }
	}
	
}

target(renderInkscape: "Renders inkscape images") {
	def exe = '/apps/Inkscape/inkscape.com';
	def asset_dir = '/git/grails-js-mud/app-assets';
	def target = 'web-app\\images\\';
	
	def EXTENTION_LENGTH = 5
	def EXTENTION = ~/.*\.svg$/
	def PATH_SEP = File.separator
	
	def root = new File("${asset_dir}");
	def targetDir = new File("${target}");	
	
	println( "Rendering...")
	root.eachFileRecurse(){
		file ->
				
		if( !(file.name =~ EXTENTION ) ) return;
		
		def asset = file.parent[root.path.length()+1..-1] + PATH_SEP + file.name[0..-EXTENTION_LENGTH]
		def assetName = asset.substring( asset.lastIndexOf(PATH_SEP)+1 )
		def assetPath = asset[0..(-1*assetName.length() -1)]
		assetPath = assetPath[assetPath.indexOf(PATH_SEP)..-1]
		def output = targetDir.absolutePath + assetPath + assetName
				
		def lastModified = 0
		
		if( targetDir.exists() ){
			def outputDir = new File(targetDir, assetPath)
			def files = outputDir.listFiles({ pdir, pname -> pname ==~ "${assetName}.*" } as FilenameFilter) 
			if( files != null && files.length > 0) lastModified = files[0].lastModified()
		}
		if( file.lastModified() < lastModified ){ 
			println("[no-change] ${output}") 
			return
		}
		
		def outputDir = new File(targetDir, assetPath) 
		if( !outputDir.exists() )
			outputDir.mkdirs();
		
		def ns = new groovy.xml.Namespace("http://www.w3.org/2000/svg", "svg");
		def inkscape = new groovy.xml.Namespace("http://www.inkscape.org/namespaces/inkscape", "inkscape");
		def svg = new XmlParser().parse(file);

		def groups = svg.g.findAll {
			return it.attributes()[inkscape.groupmode] == 'layer'; 
		}
		def layers = []
		groups.each { layers << [name:it.attributes()[inkscape.label], id:it.'@id' ] } 
		
		def run = {
			name, layer ->
			
			command = [exe, "--export-id", layer.id, "--export-id-only", "--export-area-page", "--file", file, "--export-png", output + "_" + layer.name + ".png"]
			def proc = command.execute()
			def blah = proc.in.text
			def error = proc.err.text
			if( error ){
				//println "FAILED ###\n${error}"
			}
		}
		
		def runSegment = {
			
		}
		
		if( file.name ==~ "circle.*" ){
			renderCirclePath(file, output, exe);
		}else{
			layers.each {
				println( "[rendering] ${output}_${it.name}")
				run(output, it);
			}
		}
	};
}

setDefaultTarget(renderInkscape)
